<template>
  <BasicModal
    v-bind="$attrs"
    @register="registerModal"
    :title="getTitle"
    @ok="handleSubmit"
    width="1200px"
  >
    <BasicForm @register="registerForm" />
    <a-tabs v-model:activeKey="activeKey">
      <a-tab-pane key="1" tab="存储结构">
        <vxe-toolbar>
          <template #buttons>
            <vxe-button @click="insertEvent(-1)">新增字段</vxe-button>
            <vxe-button @click="removeSelectRowEvent">删除选中</vxe-button>
          </template>
        </vxe-toolbar>
        <vxe-table
          border
          ref="xTable1"
          class="sortable-row-demo"
          :row-config="{ useKey: true }"
          :scroll-y="{ enabled: false }"
          :data="columnData"
          :edit-config="{ trigger: 'click', mode: 'cell' }"
          :checkbox-config="checkboxConfig"
          :edit-rules="validRules"
          :key="key"
        >
          <vxe-column type="checkbox" width="60" />
          <vxe-column width="60">
            <template #default>
              <span class="drag-btn">
                <i class="vxe-icon-sort"></i>
              </span>
            </template>
            <template #header>
              <vxe-tooltip content="按住后可以上下拖动排序！" enterable>
                <i class="vxe-icon-question-circle-fill"></i>
              </vxe-tooltip>
            </template>
          </vxe-column>
          <vxe-column field="sortOrder" title="排序" width="50" />
          <vxe-column
            field="columnName"
            title="字段名"
            :edit-render="{ autofocus: '.vxe-input--inner' }"
          >
            <template #edit="{ row }">
              <vxe-input
                :disabled="row.columnName == 'id'"
                v-model="row.columnName"
                type="text"
                placeholder="请输入字段名"
              />
            </template>
          </vxe-column>
          <vxe-column field="columnType" title="字段类型" :edit-render="{}">
            <template #default="{ row }">
              <span>{{ row.columnType }}</span>
            </template>
            <template #edit="{ row }">
              <vxe-select v-model="row.columnType" transfer :disabled="row.columnName == 'id'">
                <vxe-option
                  v-for="item in dictOptions"
                  :key="item.value"
                  :value="item.value"
                  :label="item.label"
                />
              </vxe-select>
            </template>
          </vxe-column>
          <vxe-column
            field="columnLength"
            title="字段长度"
            :edit-render="{ autofocus: '.vxe-input--inner' }"
          >
            <template #edit="{ row }">
              <vxe-input
                :disabled="row.columnName == 'id'"
                v-model="row.columnLength"
                type="number"
                placeholder="请输入字段长度"
              />
            </template>
          </vxe-column>
          <vxe-column
            field="columnPoint"
            title="字段小数点"
            :edit-render="{ autofocus: '.vxe-input--inner' }"
          >
            <template #edit="{ row }">
              <vxe-input
                :disabled="row.columnName == 'id'"
                v-model="row.columnPoint"
                type="number"
                placeholder="请输入字段小数点"
              />
            </template>
          </vxe-column>
          <vxe-column
            field="columnDef"
            title="默认值"
            :edit-render="{ autofocus: '.vxe-input--inner' }"
          >
            <template #edit="{ row }">
              <vxe-input
                :disabled="row.columnName == 'id'"
                v-model="row.columnDef"
                type="text"
                placeholder="请输入默认值"
              />
            </template>
          </vxe-column>
          <vxe-column
            field="columnDesc"
            title="字段备注"
            :edit-render="{ autofocus: '.vxe-input--inner' }"
          >
            <template #edit="{ row }">
              <vxe-input
                :disabled="row.columnName == 'id'"
                v-model="row.columnDesc"
                type="text"
                placeholder="请输入字段备注"
              />
            </template>
          </vxe-column>
          <vxe-column field="isNull" title="可为空" :edit-render="{}">
            <template #edit="{ row }">
              <vxe-checkbox
                :disabled="row.columnName == 'id'"
                v-model="row.isNull"
                :checked-value="1"
                :unchecked-value="0"
              />
            </template>
            <template #default="{ row }">
              <vxe-checkbox
                :disabled="row.columnName == 'id'"
                v-model="row.isNull"
                :checked-value="1"
                :unchecked-value="0"
            /></template>
          </vxe-column>
          <vxe-column field="primaryKey" title="主键" :edit-render="{}">
            <template #edit="{ row }">
              <vxe-checkbox
                :disabled="row.columnName == 'id'"
                v-model="row.primaryKey"
                :checked-value="1"
                :unchecked-value="0"
              />
            </template>
            <template #default="{ row }">
              <vxe-checkbox
                :disabled="row.columnName == 'id'"
                v-model="row.primaryKey"
                :checked-value="1"
                :unchecked-value="0"
            /></template>
          </vxe-column>
        </vxe-table>
      </a-tab-pane>
      <a-tab-pane key="2" tab="表单结构">
        <vxe-table
          border
          ref="xTable2"
          class="sortable-row-demo"
          :row-config="{ useKey: true }"
          :scroll-y="{ enabled: false }"
          :data="columnData"
          :edit-config="{ trigger: 'click', mode: 'cell' }"
          :edit-rules="validRules"
          :key="key"
        >
          <vxe-column field="sortOrder" title="排序" width="50" />
          <vxe-column field="columnName" title="字段名" />
          <vxe-column field="formModule" title="组件类型" :edit-render="{}">
            <template #default="{ row }">
              <span>{{ filterDictText(formModules, row.formModule) }}</span>
            </template>
            <template #edit="{ row }">
              <vxe-select v-model="row.formModule" transfer :disabled="row.columnName == 'id'">
                <vxe-option
                  v-for="item in formModules"
                  :key="item.value"
                  :value="item.value"
                  :label="item.label"
                />
              </vxe-select>
            </template>
          </vxe-column>
          <vxe-column field="isRequired" title="是否必填" :edit-render="{}">
            <template #edit="{ row }">
              <vxe-checkbox
                :disabled="row.columnName == 'id'"
                v-model="row.isRequired"
                :checked-value="1"
                :unchecked-value="0"
              />
            </template>
            <template #default="{ row }">
              <vxe-checkbox
                :disabled="row.columnName == 'id'"
                v-model="row.isRequired"
                :checked-value="1"
                :unchecked-value="0"
            /></template>
          </vxe-column> </vxe-table
      ></a-tab-pane>
      <a-tab-pane key="3" tab="视图结构">
        <vxe-table
          border
          ref="xTable3"
          class="sortable-row-demo"
          :row-config="{ useKey: true }"
          :scroll-y="{ enabled: false }"
          :data="columnData"
          :edit-config="{ trigger: 'click', mode: 'cell' }"
          :edit-rules="validRules"
          :key="key"
        >
          <vxe-column field="sortOrder" title="排序" width="50" />
          <vxe-column field="columnName" title="字段名" />
          <vxe-column field="searchModule" title="组件类型" :edit-render="{}">
            <template #default="{ row }">
              <span>{{ filterDictText(searchModules, row.searchModule) }}</span>
            </template>
            <template #edit="{ row }">
              <vxe-select v-model="row.searchModule" transfer :disabled="row.columnName == 'id'">
                <vxe-option
                  v-for="item in searchModules"
                  :key="item.value"
                  :value="item.value"
                  :label="item.label"
                />
              </vxe-select>
            </template>
          </vxe-column>
          <vxe-column field="isShow" title="是否显示" :edit-render="{}">
            <template #edit="{ row }">
              <vxe-checkbox
                :disabled="row.columnName == 'id'"
                v-model="row.isShow"
                :checked-value="1"
                :unchecked-value="0"
              />
            </template>
            <template #default="{ row }">
              <vxe-checkbox
                :disabled="row.columnName == 'id'"
                v-model="row.isShow"
                :checked-value="1"
                :unchecked-value="0"
            /></template>
          </vxe-column>
          <vxe-column
            field="columnWidth"
            title="显示列宽"
            :title-help="{ message: '像素(px)' }"
            :edit-render="{ autofocus: '.vxe-input--inner' }"
          >
            <template #edit="{ row }">
              <vxe-input
                :disabled="row.columnName == 'id'"
                v-model="row.columnWidth"
                type="number"
                placeholder="请输入列宽"
              />
            </template>
          </vxe-column>
          <vxe-column field="isQuery" title="是否查询" :edit-render="{}">
            <template #edit="{ row }">
              <vxe-checkbox
                :disabled="row.columnName == 'id'"
                v-model="row.isQuery"
                :checked-value="1"
                :unchecked-value="0"
              />
            </template>
            <template #default="{ row }">
              <vxe-checkbox
                :disabled="row.columnName == 'id'"
                v-model="row.isQuery"
                :checked-value="1"
                :unchecked-value="0"
            /></template>
          </vxe-column>

          <vxe-column
            field="searchSpan"
            title="查询列宽"
            :title-help="{ message: '跨距1-24(span)' }"
            :edit-render="{ autofocus: '.vxe-input--inner' }"
          >
            <template #edit="{ row }">
              <vxe-input
                :disabled="row.columnName == 'id'"
                v-model="row.searchSpan"
                type="number"
                placeholder="请输入列宽"
              />
            </template>
          </vxe-column> </vxe-table
      ></a-tab-pane>
      <!-- <a-tab-pane key="3" tab="Tab 3">Content of Tab Pane 3</a-tab-pane> -->
    </a-tabs>
  </BasicModal>
</template>
<script lang="ts">
  import {
    defineComponent,
    ref,
    computed,
    unref,
    onUnmounted,
    reactive,
    nextTick,
    watch,
  } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { formSchema } from './generateFrom.data';
  import {
    selectGenerateTableDetail,
    saveGenerateTable,
    updateGenerateTable,
  } from '/@/api/generate/generate.api';
  /* eslint-disable-next-line */
  import { VXETable, VxeTableInstance, VxeTablePropTypes } from 'vxe-table';
  import { initDictOptions, filterDictText } from '/@/utils/dict';
  import Sortable from 'sortablejs';

  export default defineComponent({
    name: 'DeptModal',
    /* eslint-disable-next-line */
    components: { BasicModal, BasicForm, VXETable },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      const dictOptions = ref<any[]>([]);
      const searchModules = ref<any[]>([]);
      const formModules = ref<any[]>([]);
      const xTable1 = ref({} as VxeTableInstance);
      const xTable2 = ref({} as VxeTableInstance);
      const xTable3 = ref({} as VxeTableInstance);
      const validRules = ref({
        columnName: [
          { required: true, message: '字段名称必填' },
          {
            pattern: /^[a-zA-Z][a-zA-Z0-9_]*$/,
            message: '只能由字母、数字、下划线组成，必须以字母开头，不能以单个字母加下划线开头',
          },
        ],
        columnType: [{ required: true, message: '字段类型必填' }],
        columnLength: [{ required: true, message: '字段长度必填' }],
        columnPoint: [{ required: true, message: '字段小数点必填' }],
      } as VxeTablePropTypes.EditRules);
      const columnData = ref<any[]>([]);

      let sortable1: any;

      const key = ref(0);
      const rowDrop = () => {
        const $table1 = xTable1.value;
        sortable1 = Sortable.create(
          $table1.$el.querySelector('.body--wrapper>.vxe-table--body tbody'),
          {
            handle: '.drag-btn',
            onEnd: (sortableEvent) => {
              let newIndex = sortableEvent.newIndex as number;
              let oldIndex = sortableEvent.oldIndex as number;
              const currRow = columnData.value.splice(oldIndex, 1)[0];
              columnData.value.splice(newIndex, 0, currRow);
              columnData.value.forEach((item, index) => {
                item.sortOrder = index + 1;
              });
              key.value++;
              console.log(columnData, 'columnData');
            },
          },
        );
      };

      let initTime: any;

      onUnmounted(() => {
        clearTimeout(initTime);
        if (sortable1) {
          sortable1.destroy();
        }
      });

      const isUpdate = ref(true);

      const [registerForm, { resetFields, setFieldsValue, updateSchema, validate }] = useForm({
        labelWidth: 100,
        baseColProps: { span: 8 },
        schemas: formSchema,
        showActionButtonGroup: false,
        compact: true,
      });

      const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
        resetFields();
        setModalProps({ confirmLoading: false });
        isUpdate.value = !!data?.isUpdate;
        if (unref(isUpdate)) {
          setFieldsValue({
            ...data.record,
          });
          updateSchema([
            {
              field: 'tableName',
              dynamicDisabled: true,
            },
          ]);
        } else {
          updateSchema([
            {
              field: 'tableName',
              dynamicDisabled: false,
            },
          ]);
        }
        //加载拖动事件
        watch(
          key,
          () => {
            if (sortable1) {
              sortable1.destroy();
              sortable1 = null;
            }
            console.log(111);
            nextTick(() => {
              rowDrop();
            });
          },
          { immediate: true },
        );
        //如果是更新则获取明细数据
        if (unref(isUpdate)) {
          selectGenerateTableDetail(data.record).then((res) => {
            columnData.value = res;
          });
        } else {
          columnData.value = [
            {
              columnName: 'id',
              columnType: 'string',
              columnLength: 50,
              columnPoint: 0,
              columnDef: '',
              columnDesc: '主键',
              isNull: 0,
              primaryKey: 1,
              sortOrder: 1,
              isQuery: 0,
              isShow: 0,
              isRequired: 0,
              searchModule: 'Input',
              formModule: 'Input',
              columnWidth: 100,
              searchSpan: 8,
            },
          ];
        }
        const dictData = initDictOptions('column_type');
        dictData.then((res) => {
          dictOptions.value = res;
        });
        initDictOptions('form_module').then((res) => {
          formModules.value = res;
        });
        initDictOptions('search_module').then((res) => {
          searchModules.value = res;
        });
      });

      const insertEvent = async (row) => {
        const $table = xTable1.value;
        if ($table) {
          const record = {
            sortOrder: columnData.value.length + 1,
            columnType: 'string',
            columnLength: 50,
            columnPoint: 0,
            columnName: '',
            columnDef: '',
            columnDesc: '',
            isNull: 0,
            primaryKey: 0,
            isQuery: 0,
            isShow: 1,
            isRequired: 0,
            searchModule: 'Input',
            formModule: 'Input',
            columnWidth: 100,
            searchSpan: 8,
          };
          columnData.value.push(record);
          const { row: newRow } = await $table.insertAt(record, row);
          await $table.setEditCell(newRow, 'name');
        }
      };
      const removeSelectRowEvent = () => {
        const $table = xTable1.value;
        if ($table) {
          // $table.removeCheckboxRow();
          const selectedRows = $table.getCheckboxRecords(); // 获取选中的行数据

          // 获取选中行的下标
          const selectedIndexes = selectedRows.map((row) => $table.getRowIndex(row));

          // 更新数据源，删除选中的行数据
          $table.removeCheckboxRow();

          // 同时删除数据
          selectedIndexes.sort((a, b) => b - a); // 降序排列下标，以便正确删除数据
          selectedIndexes.forEach((index) => {
            columnData.value.splice(index, 1); // 删除对应下标的数据

            //重新计算排序
            columnData.value.forEach((item, index) => {
              item.sortOrder = index + 1;
            });
          });
        }
      };

      const checkboxConfig = reactive({
        labelField: 'name',
        checkMethod: ({ row }) => {
          return row.columnName !== 'id';
        },
      });

      const getTitle = computed(() => (!unref(isUpdate) ? '新增配置' : '编辑配置'));

      async function handleSubmit() {
        try {
          const $table = xTable1.value;
          const errMap = await $table.validate(true);
          if (errMap) {
            VXETable.modal.message({ status: 'error', content: '校验不通过！' });
            return;
          }
          const values = await validate();
          console.log('columnData', columnData);
          setModalProps({ confirmLoading: true });
          if (unref(isUpdate)) {
            await updateGenerateTable({
              generateDevMain: values,
              generateDevDetail: columnData.value,
            });
          } else {
            await saveGenerateTable({
              generateDevMain: values,
              generateDevDetail: columnData.value,
            });
          }
          closeModal();
          emit('success');
        } finally {
          setModalProps({ confirmLoading: false });
        }
      }

      return {
        filterDictText,
        formModules,
        searchModules,
        validRules,
        checkboxConfig,
        removeSelectRowEvent,
        insertEvent,
        dictOptions,
        columnData,
        xTable1,
        rowDrop,
        registerModal,
        registerForm,
        getTitle,
        handleSubmit,
        activeKey: ref('1'),
        key,
        xTable2,
        xTable3,
      };
    },
  });
</script>
